package ws

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"nhooyr.io/websocket"
	"nhooyr.io/websocket/wsjson"
	"time"
)

// 聊天室

type ChatRoom struct {
}

func NewChatRoom() ChatRoom {
	return ChatRoom{}
}

// 连接ws处理函数
func (cr *ChatRoom) WsConnHandle(c *gin.Context) {
	// 用于设置请求源 TODO 这个不是办法，还得找方法
	c.Request.Header.Set("Origin", "http://localhost:8899")
	conn, err := websocket.Accept(c.Writer, c.Request, nil)
	if err != nil {
		return
	}
	defer conn.Close(websocket.StatusInternalError, "内部出错了")
	// 设置连接超时时间
	ctx, cancelFunc := context.WithTimeout(c.Request.Context(), time.Second*10)
	defer cancelFunc()

	var v interface{}
	//if err = wsjson.Read(ctx, conn, &v); err != nil {
	//	return
	//}
	fmt.Printf("接收客户端：%v\n", v)

	if err = wsjson.Write(ctx, conn, "Hello websocket client"); err != nil {
		return
	}
	conn.Close(websocket.StatusNormalClosure, "")

}
